import os
import re
from datetime import datetime


def get_html_files(folder_path):
    """获取指定文件夹下的所有HTML文件"""
    html_files = []
    for file in os.listdir(folder_path):
        if file.endswith('.html'):
            html_files.append(file)
    return html_files


def extract_info_from_filename(filename):
    """从文件名中提取标题和日期"""
    # 支持三种日期格式:
    # 1. "标题-YYYY年MM月DD日.html"
    # 2. "标题-YYYY-MM-DD.html"
    # 3. "标题-发布时间：YYYY年MM月DD日.html"
    patterns = [
        r'^(.*?)-(\d{4}年\d{1,2}月\d{1,2}日)\.html$',
        r'^(.*?)-(\d{4}-\d{1,2}-\d{1,2})\.html$',
        r'^(.*?)-发布时间：(\d{4}年\d{1,2}月\d{1,2}日)\.html$'
    ]

    for pattern in patterns:
        match = re.match(pattern, filename)
        if match:
            title = match.group(1)
            date_str = match.group(2)

            # 根据不同日期格式进行解析
            try:
                if '年' in date_str:
                    date_obj = datetime.strptime(date_str, '%Y年%m月%d日')
                    # 统一日期字符串格式
                    date_str = date_obj.strftime('%Y年%m月%d日')
                else:
                    date_obj = datetime.strptime(date_str, '%Y-%m-%d')
                    # 转换为"YYYY年MM月DD日"格式
                    date_str = date_obj.strftime('%Y年%m月%d日')

                return title, date_str, date_obj, filename
            except ValueError:
                # 日期格式无效，继续尝试下一个模式
                continue

    return None, None, None, filename


def generate_news_data(folder_path):
    """生成新闻数据并按日期倒序排序"""
    html_files = get_html_files(folder_path)
    news_items = []

    for file in html_files:
        title, date_str, date_obj, filename = extract_info_from_filename(file)
        if title and date_str:
            news_items.append({
                'title': title,
                'date': date_str,
                'file': folder_path+"/"+filename,
                'date_obj': date_obj  # 用于排序
            })

    # 按日期倒序排序
    news_items.sort(key=lambda x: x['date_obj'], reverse=True)

    # 生成JavaScript格式的代码
    js_code = '// 定义新闻数据 - 自动生成\nconst newsData = [\n'
    for item in news_items:
        js_code += f'  {{\n'
        js_code += f'    title: "{item["title"]}",\n'
        js_code += f'    date: "{item["date"]}",\n'
        js_code += f'    file: "{item["file"]}"\n'
        js_code += f'  }},\n'
    js_code += '];'

    return js_code


if __name__ == "__main__":
    folder_path = r"D:\aGetDataFrom111111\中储发展股份有限公司网站\05党群工作\党群工作-中储"

    news_data = generate_news_data(folder_path)
    print("\n生成的新闻数据:\n")
    print(news_data)

    # 保存到文件
    output_file = os.path.join(folder_path, "news_data.js")
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(news_data)
    print(f"\n数据已保存到: {output_file}")